package com.spring.demo.service;

import com.alibaba.fastjson.JSONObject;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.pipeline.ConsolePipeline;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Selectable;

import java.util.List;

public class OschinaBlogPageProcessor implements PageProcessor {
    private Site site = Site
            .me()
            //设置超时时间，单位是毫秒
            .setSleepTime(3000)
            //设置UserAgent
            .setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36");

    @Override
    public void process(Page page) {

        Selectable selectable = page.getHtml().xpath("//div[@class=\"classify_books\"]");

        List<Selectable> nodes = selectable.nodes();
        for (Selectable selectableNode : nodes) {
            //一级标题
            String oneTitle = selectableNode.$("h3[class^=\"classify_title\"] > a", "text").toString();
            System.out.println("======" + oneTitle);
            Selectable selectable2 = selectableNode.xpath("//div[@class=\"classify_kind\"]");
            for (Selectable selectable2C : selectable2.nodes()) {
                //二级标题
                String twoTitle = selectable2C.xpath("/div/div/a/text()").toString();
                System.out.println("============" + twoTitle);
                //三级标题
                List<String> threeTitle = selectable2C.xpath("//li[@name=\"cat_3\"]/a/text()").all();
                System.out.println("====================================" + JSONObject.toJSONString(threeTitle));
//                List<String> threeTitle2= selectable2C.xpath("//li[@name=\"cat_3\"]/a").links().all();
//                System.out.println("====================================" + JSONObject.toJSONString(threeTitle2));
            }
        }
    }

    @Override
    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {
        Spider.create(new OschinaBlogPageProcessor())
                .addUrl("http://category.dangdang.com/?ref=www-0-C")
                .addPipeline(new ConsolePipeline())
                .run();
    }
}

